package android.mcsmtms.fragment;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.mcsmtms.R;
import android.mcsmtms.activity.NotificationDetailsActivity;
import android.mcsmtms.activity.SendReportActivity;
import android.mcsmtms.constant.GlobalConstants;
import android.mcsmtms.constant.GlobalConstants.Roads;
import android.mcsmtms.constant.GlobalConstants.UserTypes;
import android.mcsmtms.domain.SituationReport;
import android.mcsmtms.domain.User;
import android.mcsmtms.rest.RestClient;
import android.mcsmtms.util.JsonHelper;
import android.mcsmtms.util.Utilities;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;

public class NotificationsFragment extends Fragment {
	// This is the Adapter being used to display the list's notificationList
	// SimpleCursorAdapter mAdapter;
	private ListView situationReportList;
	private NotificationsCustomAdapter notificationsCustomAdapter;
	private ArrayList<SituationReport> situationReportArray = new ArrayList<SituationReport>();
	private User loggedUser;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_notifications, container, false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		loggedUser = Utilities.getLoggedUser(this.getActivity());
		getNotifications();
	};

	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onPrepareOptionsMenu(menu);
	}
	
	public void getNotifications() {
		GetNotificationsTask getNotificationsTask = new GetNotificationsTask(false, loggedUser.getUserType());
		getNotificationsTask.execute((Void) null);
	}
	
	class RefreshNotificationsListCallBackImpl implements RefreshNotificationListCallback {
	    /* (non-Javadoc)
		 * @see android.mcsmtms.fragment.RefreshNotificationListCallback#refreshNotificationsList()
		 */
	    @Override
		public void refreshNotificationsList() {
	        getNotifications();
	    }
	}
	
	public class GetNotificationsTask extends AsyncTask<Void, Void, List<SituationReport>> {
		private String NOTIFICATIONS_URL = GlobalConstants.RestUrls.NOTIFICATIONS_URL;
		
		private ProgressDialog dialog;
		private boolean isRefresh = false;
		private String userType;
		
		public GetNotificationsTask(boolean isRefreshOperation, String userType) {
			isRefresh = isRefreshOperation;
			if(UserTypes.valueOf(userType) == UserTypes.BAYANAN_SCOUT)
				NOTIFICATIONS_URL += Roads.BAYAN_BAYANAN.getCode();
			else if(UserTypes.valueOf(userType) == UserTypes.EROD_SCOUT)
				NOTIFICATIONS_URL += Roads.E_RODRIGUEZ.getCode();
			else if(UserTypes.valueOf(userType) == UserTypes.ESANTOS_SCOUT)
				NOTIFICATIONS_URL += Roads.E_SANTOS.getCode();
			else if(UserTypes.valueOf(userType) == UserTypes.JMOLINA_SCOUT)
				NOTIFICATIONS_URL += Roads.J_MOLINA.getCode();
			else if(UserTypes.valueOf(userType) == UserTypes.JPRIZAL_SCOUT)
				NOTIFICATIONS_URL += Roads.JP_RIZAL.getCode();
		}
		
		@SuppressWarnings("unchecked")
		@Override
		protected List<SituationReport> doInBackground(Void... params) {
			List<SituationReport> notificationList = null;
			
			try {
				// Simulate network access.
				//Thread.sleep(2000);
				RestClient client = new RestClient(NOTIFICATIONS_URL, loggedUser.getUserName(), loggedUser.getPassword());
				
			    client.execute(RestClient.RequestMethod.GET);
				
				String notificationDetailsResponse = client.getResponse();
				notificationList = (List<SituationReport>) JsonHelper.getObject(notificationDetailsResponse, new TypeToken<List<SituationReport>>(){}.getType(), "notificationList");
				
			} catch (Exception ex) {
				//Toast.makeText(getActivity(), "Error in rendering hazard hazardMap!", Toast.LENGTH_SHORT).show();
				Log.e("Notifications Download Error", "Error in downloading Notification details: " + Utilities.getErrorMessage(ex));
				return null;
			}
			
			return notificationList;
		}
		
		@SuppressWarnings("unchecked")
		@Override
		protected void onPostExecute(List<SituationReport> notificationList) {
			super.onPostExecute(notificationList);
			situationReportList = (ListView) getActivity().findViewById(R.id.listView);
			
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			
			if(notificationList == null) {
				Utilities.showDefaultAlertDialog(getActivity(), "Error", "Error in downloading notification list. Tap refresh button to retry.");
			} else {
				try {
					if(notificationList != null && notificationList.size() > 0) {
//						for(SituationReport situationReport : notificationList) {
//							for(SituationSegment situationSegment : situationReport.getSituationSegmentList()) {
//								
//							}
//						}
						/**
						 * set item into adapter
						 */
						notificationsCustomAdapter = new NotificationsCustomAdapter(
								getActivity(), R.layout.row, notificationList, new RefreshNotificationsListCallBackImpl());
						
						situationReportList.setItemsCanFocus(false);
						situationReportList.setAdapter(notificationsCustomAdapter);
							
						/**
						 * get on item click listener
						 */
						// situationReportList.setOn
						situationReportList.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> parent, View v,
									final int position, long id) {
								Log.i("List View Clicked", "**********");
//								Toast.makeText(getActivity(), "List View Clicked:" + position,
//										Toast.LENGTH_LONG).show();
								
								Intent goToNotifDetailsIntent = new Intent(getActivity(), NotificationDetailsActivity.class);
								goToNotifDetailsIntent.putExtra("notification", (SituationReport) situationReportList.getItemAtPosition(position));
								getActivity().startActivity(goToNotifDetailsIntent);
							}
						});
												
					} else {
						Toast.makeText(getActivity(), "No notifications available", Toast.LENGTH_LONG).show();
						//situationReportList.setEmptyView(situationReportList);
						situationReportList.setAdapter(null);
					} 
						
				} catch (Exception ex) {
					ex.printStackTrace();
					Log.e("Notifications Error", "Error in displaying notifications: " + Utilities.getErrorMessage(ex));
					Utilities.showDefaultAlertDialog(getActivity(), "Error", "Error in displaying notification list. Tap refresh button to retry.");
				}
			}
		}

		@Override
		protected void onCancelled() {
//			mAuthTask = null;
//			showProgress(false);
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(getActivity());
			dialog.setCancelable(false);
			dialog.setMessage("Loading..");
			dialog.isIndeterminate();
			dialog.show();
		}
	}
}
